package com.unitech.drinks.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unitech.drinks.exception.BusinessErrorCode;
import com.unitech.drinks.exception.BusinessException;
import com.unitech.drinks.mapper.CategoryMapper;
import com.unitech.drinks.model.Category;
import com.unitech.drinks.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class MysqlCategoryService implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageInfo<Category> listCategories(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(categoryMapper.selectAll());
    }

    @Override
    public Category showCategory(Integer id) {
        Category exitsCategory = categoryMapper.selectByPrimaryKey(id);
        if (exitsCategory == null) { // 不存在抛出业务错误
            throw new BusinessException(BusinessErrorCode.CATEGORY_NOT_FOUND);
        }
        return exitsCategory;
    }

    @Override
    public Category createCategory(Category category) {
        // 查询是否有同名分类
        Example example = new Example(Category.class);
        example.createCriteria().andEqualTo("name", category.getName().trim());
        List<Category> categoryList = categoryMapper.selectByExample(example);
        if (categoryList.size() > 0) { // 如果存在，抛出业务错误
            throw new BusinessException(BusinessErrorCode.CATEGORY_EXISTS);
        }

        // 新建数据
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public Category modifyCategory(Category category) {
        Category exitsCategory = categoryMapper.selectByPrimaryKey(category.getId());
        if (exitsCategory == null) { // 不存在抛出业务错误
            throw new BusinessException(BusinessErrorCode.CATEGORY_NOT_FOUND);
        }

        categoryMapper.updateByPrimaryKey(category);
        return category;
    }

    @Override
    public void deleteCategory(Integer id) {
        Category exitsCategory = categoryMapper.selectByPrimaryKey(id);
        if (exitsCategory == null) { // 不存在抛出业务错误
            throw new BusinessException(BusinessErrorCode.CATEGORY_NOT_FOUND);
        }

        categoryMapper.deleteByPrimaryKey(id);
    }
}
